package com.cdp.zwy.zwy_manager_back_v1.service;

import com.cdp.zwy.zwy_manager_back_v1.mapper.ArticleMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Set;

/**
 * @author zwy
 * @version 1.0
 * @description: ScheduledTaskService定时任务服务
 * actor 数据持久化的守护者
 * @date 2025/8/20 17:05
 */

@Service
public class ScheduledTaskService {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTaskService.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ArticleMapper articleMapper;

    private static final String ARTICLE_LIKES_KEY_PREFIX = "article:likes:";

    /**
     * 定时将 Redis 中的文章点赞数同步到 MySQL 数据库
     * cron 表达式: "表示每10分钟执行一次"
    */
    @Scheduled(cron = "0 */10 * * * ?")
    public void syncLikesFromRedisToDb() {
        log.info("开始执行点赞数据同步任务...");
        try {
            Set<String> likeKeys = stringRedisTemplate.keys(ARTICLE_LIKES_KEY_PREFIX + "*");
            if (likeKeys == null || likeKeys.isEmpty()) {
                log.info("没有需要同步的点赞数据。");
                return;
            }

            for (String key : likeKeys) {
                Integer articleId = Integer.parseInt(key.substring(ARTICLE_LIKES_KEY_PREFIX.length()));
                Long likeCount = stringRedisTemplate.opsForSet().size(key);

                if (likeCount != null) {
                    articleMapper.updateLikes(articleId, likeCount.intValue());
                    log.info("文章 ID: {}, 点赞数: {} 已同步到数据库。", articleId, likeCount);
                }
            }
            log.info("点赞数据同步任务执行完毕。");
        } catch (Exception e) {
            log.error("点赞数据同步任务执行失败。", e);
        }
    }
}

